﻿using System;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Web.UI.WebControls;
using H2.NET.Common;

namespace H2.NET.Web.Workflow
{
    public partial class InboxStore : DwzCode.BasePage
    {
        #region 属性 public
        private DataTable dt = new DataTable();
        private DataTable allProcess = new DataTable();

        [SessionType]
        string strProcessName = "";

        public string Type
        {
            get
            {
                return this.ViewState["Type"] == null ? "" : (String)this.ViewState["Type"];
            }
            set
            {
                this.ViewState["Type"] = value;
            }
        }

        private string DatabaseName
        {
            get
            {
                if (Application["DBName"] == null)
                {
                    var connStr = H2.NET.Util.ConnectionStrings("oleDB");
                    var conn = new OleDbConnection(connStr);
                    Application["DBName"] = conn.Database;
                    conn.Dispose();
                }
                return Application["DBName"] as string;
            }
        }
        #endregion

        #region 事件 页面 加载
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                strProcessName = Request.QueryString["process"];

                load_gv_inbox_list();
                //第一次加载页面时初始化
                hf_type.Value = AksRequest.GetString("drpProcess").Trim();
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 Page_Load 事件出错：" + ee.Message);
            }
        }
        #endregion


        private string BuildSqlStr()
        {
            string strUserName = clsCmm.comm_username;
            string strSummary = tb_Summary.Text.Trim().Replace(",", "',").Replace("'", "''");
            string strIncidentNoFrom = txtIncidentFrom.Value;
            string strIncidentNoTo = txtIncidentTo.Value;
            string BusinessKey = AksRequest.GetQueryString("BusinessKey");

            //查询过滤中Process下拉列表中的值
            string strProcess = "all";
            if (drpProcess.SelectedItem != null)
            {
                strProcess = drpProcess.SelectedItem.Value.Trim();
            }

            //查询过滤中流程步骤的值
            string strStep = "all";
            if (drpStep.SelectedItem != null)
            {
                strStep = drpStep.SelectedItem.Value.Trim();
            }

            //查找收件箱列表
            var sql = new System.Text.StringBuilder();
            sql.AppendLine(@"select top 50 a.*,(case  when abortuser in ('magics11', '张佩华(Zhang Pei Hua)') then 'itss' else abortuser end) abortuser from (select top 50 [Priority],taskid,processname3,processname,
helpurl,openform,s.incident,steplabel,taskuser,assignedtouser,img_status,img_monitor,s.status,substatus,starttime,delaytime,overduetime,urgentduetime,summary,initiator,case when s.status1 = 33 and t.status = 'active' then '1' ELSE status1  end status1,initiator_name,taskuser_name,assignedtouser_name from (SELECT CASE ISNULL(ISNULL(p.DMO_Priority, p.Business_Priority), 3)
                                  WHEN 1 THEN 'Urgent'
                                  WHEN 2 THEN 'High'
                                  WHEN 3 THEN 'Routine'
                                END AS [Priority] ,
                                RTRIM(a.taskid) AS taskid ,");
            if (clsCmm.comm_language == "en-us" && Util.AppSettings("language").ToLower() == "yes")
            {
                sql.AppendLine(" h.processhelpurl as processname3,");
            }
            else
            {
                sql.AppendLine(" a.processname as processname3,");
            }
            sql.AppendLine(" h.processname,");
            sql.AppendLine(@"RTRIM(a.helpurl) AS helpurl ,
                                '' AS openform ,
                                a.incident ,
                                a.steplabel ,
                                a.taskuser ,
                                a.assignedtouser ,
                                '' AS img_status ,
                                '' AS img_monitor ,
                                a.status ,
                                a.substatus ,
                                a.starttime ,
                                a.delaytime ,
                                a.overduetime ,
                                DATEDIFF(s, GETDATE(), a.urgentduetime) AS urgentduetime ,
                                c.summary ,
                                c.initiator ,
                                c.status status1,
                                '' AS initiator_name ,
                                '' AS taskuser_name ,
                                '' AS assignedtouser_name");
            sql.AppendLine(string.Format(@"FROM    tasks a with(nolock)
                                        LEFT JOIN {0}.dbo.mdc_Priority p ON a.PROCESSNAME = p.Process
                                                                                    AND p.Incident = a.INCIDENT
                                                                                    AND a.taskid NOT IN (
                                                                                    SELECT  taskid
                                                                                    FROM    taskqueue )
                                        INNER JOIN dbo.INITIATE  h WITH (NOLOCK) ON a.PROCESSNAME = h.PROCESSNAME
                                                                     AND H.PROCESSNAME IN (
                                                                     SELECT [PROCESSNAME]
                                                                     FROM   [PROCESSES]
                                                                     WHERE  [PROCESSES].[DESCRIPTION] IN (
                                                                            SELECT  KeyWords
                                                                            FROM    BPMSYSTEM
                                                                            WHERE   Platform = '{1}' ) )
                                        LEFT JOIN incidents c with(nolock) ON a.processname = c.processname
                                                                 AND a.incident = c.incident
                                WHERE   1 = 1", DatabaseName, Util.AppSettings("platform")));
            sql.AppendLine(" and a.status = 1 ");

            sql.Append(")  as s join  (select DISTINCT Process,Incident,status from " +
                          DatabaseName+".dbo.t_smd_ChildProcess a where a.BusinessKey = '" + BusinessKey + "' and status = 'active') T ON S.processname = t.Process and s.incident = t.incident" +
                          " order by taskid asc,s.incident asc ");

            sql.AppendLine(@" union all  select top 50 [Priority],taskid,processname3,processname,
helpurl,openform,s1.incident,steplabel,taskuser,assignedtouser,img_status,img_monitor,s1.status,substatus,starttime,delaytime,overduetime,urgentduetime,summary,initiator,case when s1.status1 = 33 and t1.status = 'finish' then '2' when  s1.status1 = 33 and t1.status = 'abort' then 4 ELSE status1  end status1,initiator_name,taskuser_name,assignedtouser_name from (SELECT CASE ISNULL(ISNULL(p.DMO_Priority, p.Business_Priority), 3)
                                  WHEN 1 THEN 'Urgent'
                                  WHEN 2 THEN 'High'
                                  WHEN 3 THEN 'Routine'
                                END AS [Priority] ,
                                RTRIM(a.taskid) AS taskid ,");
            if (clsCmm.comm_language == "en-us" && Util.AppSettings("language").ToLower() == "yes")
            {
                sql.AppendLine(" h.processhelpurl as processname3,");
            }
            else
            {
                sql.AppendLine(" a.processname as processname3,");
            }
            sql.AppendLine(" h.processname,");
            sql.AppendLine(@"RTRIM(a.helpurl) AS helpurl ,
                                '' AS openform ,
                                a.incident ,
                                a.steplabel ,
                                a.taskuser ,
                                a.assignedtouser ,
                                '' AS img_status ,
                                '' AS img_monitor ,
                                a.status ,
                                a.substatus ,
                                a.starttime ,
                                a.delaytime ,
                                a.overduetime ,
                                DATEDIFF(s, GETDATE(), a.urgentduetime) AS urgentduetime ,
                                c.summary ,
                                c.initiator ,
                                c.status status1 ,
                                '' AS initiator_name ,
                                '' AS taskuser_name ,
                                '' AS assignedtouser_name");
            sql.AppendLine(string.Format(@"FROM    tasks a with(nolock)
                                        LEFT JOIN {0}.dbo.mdc_Priority p ON a.PROCESSNAME = p.Process
                                                                                    AND p.Incident = a.INCIDENT
                                                                                    AND a.taskid NOT IN (
                                                                                    SELECT  taskid
                                                                                    FROM    taskqueue )
                                        INNER JOIN dbo.INITIATE h WITH (NOLOCK) ON a.PROCESSNAME = h.PROCESSNAME
                                                                     AND H.PROCESSNAME IN (
                                                                     SELECT [PROCESSNAME]
                                                                     FROM   [PROCESSES]
                                                                     WHERE  [PROCESSES].[DESCRIPTION] IN (
                                                                            SELECT  KeyWords
                                                                            FROM    BPMSYSTEM
                                                                            WHERE   Platform = '{1}' ) )
                                        LEFT JOIN incidents c with(nolock) ON a.processname = c.processname
                                                                 AND a.incident = c.incident
                                WHERE   1 = 1", DatabaseName, Util.AppSettings("platform")));
            sql.AppendLine(" and CHARINDEX('B', a.STEPID) > 0 ");

            sql.Append(")  as s1 join  (select DISTINCT Process,Incident,status from " +
                          DatabaseName + ".dbo.t_smd_ChildProcess a where a.BusinessKey = '" + BusinessKey + "' ) T1 ON S1.processname = t1.Process and s1.incident = t1.incident where t1.status = 'finish' or (s1.status1 = 4)" +
                          " order by taskid asc,s1.incident asc )as a left join " + DatabaseName + ".dbo.t_smd_Childprocess cp on cp.incident = a.incident and cp.process = a.processname ");

            TaskDB.Log("", true, "调用 inboxStore.aspx 页面 BuildSqlStr 方法SQL：" + sql.ToString());
            return sql.ToString();
        }

        private string AppendForCount(string sqlStr)
        {
            return string.Format("select count(1) from ({0}) sub", sqlStr);
        }

        private string AppendForPaged(string sqlstr, int start, int end)
        {
            string orderby = "starttime desc";

            return string.Format(";with temp as(\r\n" +
                "	select row_number() over(order by sub.{3}) as rownum, sub.* from ({0}) sub\r\n)\r\n" +
                "select * from temp where rownum between {1} and {2}", sqlstr, start, end, orderby);
        }

        private DataTable PagedQuery()
        {
            clsCmm.clsDB.Storage("bpmDB");
            string sql = BuildSqlStr();
            TotalItemCount = Convert.ToInt32(clsCmm.clsDB.Query(AppendForCount(sql)).Rows[0][0]);
            PageNumber = 1;

            Pager1.TotalItemCount = TotalItemCount;
            Pager1.PageSize = PageSize;
            Pager1.PageNumber = PageNumber;
            dt = clsCmm.clsDB.Query(AppendForPaged(sql, PageSize * (PageNumber - 1) + 1, PageSize * PageNumber));

            return dt;
        }

        #region 方法 查询并对列表进行数据绑定
        public void load_gv_inbox_list()
        {
            try
            {
                //加载列表
                dt = PagedQuery();
                allProcess = get_all_process();
                initSelectItem();
                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                #region added by zk 2009-12-21 start
                //取得所有的用户账号对应用户姓名             
                string str_user_name = "";
                DataTable dt2 = new DataTable();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //initiator
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'";
                    }

                    //taskuser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'";
                    }

                    //assignedtouser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'";
                    }
                }

                //从数据库中查询用户信息
                string strSQL = "select rtrim(FULLNAME) as UserFullName,lower(rtrim(Name)) as UserShortName from JOBS where lower(rtrim(Name)) in('-1'" + str_user_name + ")";
                clsCmm.clsDB.Storage("bpmDB");
                dt2 = clsCmm.clsDB.Query(strSQL);
                #endregion added by zk 2009-12-21 end

                //设置状态列的图片
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //处理表单类型 (自定义表单 & 标准表单)
                    string HelpUrl = dt.Rows[i]["helpurl"].ToString();
                    if (!string.IsNullOrEmpty(HelpUrl) && HelpUrl.Length >= 5 && HelpUrl.Substring(0, 5).ToLower() == "form:")
                    {
                        dt.Rows[i]["openform"] = HelpUrl.Substring(5, HelpUrl.Length - 5);
                    }
                    else
                    {
                        dt.Rows[i]["openform"] = "workflow/openform.aspx";
                    }

                    #region SMD项目特殊处理

                    var processName = dt.Rows[i]["processname"].ToString().Trim();
                    if (processName == "New Store Application" ||
                        processName == "Store Deposit Change" ||
                        processName == "Store Deposit Receive" ||
                        processName == "New Store Deposit Receive" ||
                        processName == "Store Data Change")
                    {
                        dt.Rows[i]["openform"] = "pages/smd/taskview.aspx";
                    }

                    #endregion

                    #region added by zk 2009-12-21 start
                    //循环设置用户信息
                    for (int j = 0; j < dt2.Rows.Count; j++)
                    {
                        //initiator
                        if (dt.Rows[i]["initiator"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["initiator_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //taskuser
                        if (dt.Rows[i]["taskuser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["taskuser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //assignedtouser
                        if (dt.Rows[i]["assignedtouser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["assignedtouser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }
                    }
                    #endregion added by zk 2009-12-21 end

                    //流程状态图标
                    switch (dt.Rows[i]["substatus"].ToString().Trim())
                    {
                        case "0":
                        case "1":
                            dt.Rows[i]["img_status"] = "frm_inbox_late.gif";
                            break;

                        case "2":
                            dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                            break;

                        case "3":
                            dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                            break;

                        case "4":
                            dt.Rows[i]["img_status"] = "frm_inbox_aborted.gif";
                            break;

                        case "7":
                            dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                            break;

                        case "8":
                            dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                            break;

                        case "16":
                            dt.Rows[i]["img_status"] = "frm_inbox_returned.gif";
                            break;

                        case "32":
                            dt.Rows[i]["img_status"] = "frm_inbox_resubmitted.gif";
                            break;

                        case "12":
                            dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                            break;

                        default:
                            dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                            break;
                    }
                    

                    //判断是否为指派、会办的任务类型
                    if (dt.Rows[i]["taskuser"].ToString() != dt.Rows[i]["assignedtouser"].ToString())
                    {
                        dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                    }

                    //是否显示监控图标
                    if (dt.Rows[i]["taskid"] == DBNull.Value || dt.Rows[i]["taskid"].ToString().Trim() == "")
                    {
                        dt.Rows[i]["img_monitor"] = "frm_initiate_blank.gif";
                        dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                    }
                    else
                    {
                        dt.Rows[i]["img_monitor"] = "bpmview.gif";
                    }
                    switch (dt.Rows[i]["status1"].ToString().Trim())
                    {
                        case "1":
                            dt.Rows[i]["img_status"] = "frm_inbox_late.gif";
                            break;
                        case "2":
                            dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                            break;
                        case "4":
                            dt.Rows[i]["img_status"] = "frm_inbox_aborted.gif";
                            break;
                        case "33":
                            dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                            break;
                    }

                }

                //第一次没有排序字段的情况
                if (ViewState["OrderBy"] == null)
                {
                    dt.DefaultView.Sort = "starttime DESC";
                }
                else
                {
                    dt.DefaultView.Sort = ViewState["OrderBy"] + " " + ViewState["Order"];
                }

                gvInbox.DataSource = dt;
                gvInbox.DataBind();
                

            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_gv_inbox_list 方法出错：" + ee.Message);
            }
        }
        #endregion

        public void load_drp_control_list()
        {
            try
            {
                //清空现有列表
                drpProcess.Items.Clear();

                //增加第一行
                drpProcess.Items.Add(new ListItem("All", "all"));

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

            }
            catch (Exception ex)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_drp_control_list方法出错：" + ex.Message);
            }
        }

        #region 获取全部流程
        public DataTable get_all_process()
        {
            string strSQL = @"SELECT DISTINCT  a.processname FROM    tasks a WITH (NOLOCK)
LEFT JOIN initiate h WITH (NOLOCK) ON a.processname = h.processname
LEFT JOIN dbo.PROCESSES p WITH (NOLOCK) ON h.PROCESSNAME = p.PROCESSNAME
LEFT JOIN dbo.INCIDENTS i WITH (NOLOCK) ON h.PROCESSNAME = i.PROCESSNAME AND a.INCIDENT = i.INCIDENT
LEFT JOIN dbo.BPMSYSTEM s WITH (NOLOCK) ON p.DESCRIPTION = s.KeyWords
LEFT JOIN dbo.TASKQUEUE tq WITH (NOLOCK) ON a.TASKID = tq.TASKID
WHERE     a.assignedtouser = '{username}' COLLATE Chinese_PRC_CI_AI
AND tq.TASKID IS NULL
AND s.Platform = 'MDC'
AND CHARINDEX('B', a.STEPID) > 0
AND i.initiator = '{username}' COLLATE Chinese_PRC_CI_AI ";
            strSQL = strSQL.Replace("{username}", clsCmm.comm_username);
            TaskDB.Log("", true, "调用 inbox.aspx 页面 get_all_inbox 方法SQL：" + strSQL);

            clsCmm.clsDB.Storage("bpmDB");
            allProcess = clsCmm.clsDB.Query(strSQL);
            return allProcess;
        }
        #endregion

        #region 获取流程的step
        public DataTable getStepByProcess(string process)
        {
            string strSQL = "select * from [PROCESSSTEPS] where processname='" + process + "' and steptype not in (2,3,5,7)";
            clsCmm.clsDB.Storage("bpmDB");
            return clsCmm.clsDB.Query(strSQL);
        }
        #endregion

        #region 加载选项卡的数据
        public void initSelectItem()
        {
            #region 加载drpProcess选项
            try
            {

                string oldProcess = drpProcess.SelectedValue;
                //清空现有列表
                drpProcess.Items.Clear();

                //增加第一行
                drpProcess.Items.Add(new ListItem("All", "all"));

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                #region 获取全部流程的流程名称
                for (int i = 0; i < allProcess.Rows.Count; i++)
                {
                    bool Flg = true;

                    //流程名称下拉列表
                    foreach (ListItem item in drpProcess.Items)
                    {
                        if (allProcess.Rows[i]["processname"].ToString() == item.Value)
                        {
                            Flg = false;
                            break;
                        }
                    }

                    //如果不存在的情况
                    if (Flg)
                    {
                        drpProcess.Items.Add(new ListItem(GetCache(allProcess.Rows[i]["processname"].ToString().Trim()), allProcess.Rows[i]["processname"].ToString().Trim()));
                    }
                }
                if (!oldProcess.Equals("all"))
                {
                    drpProcess.SelectedValue = oldProcess;
                }
                #endregion
            }
            catch (Exception ex)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_drp_control_list方法出错：" + ex.Message);
            }
            #endregion

            #region 加载processStep选项
            processStep();
            #endregion
        }

        #region processStep
        public void processStep()
        {
            String oldStep = drpStep.SelectedValue.Trim();
            drpStep.Items.Clear();
            //增加第一行
            drpStep.Items.Add(new ListItem("All", "all"));
            if (drpProcess.SelectedItem != null && drpProcess.SelectedItem.Value != "all")
            {
                DataTable steps = getStepByProcess(drpProcess.SelectedItem.Value.Trim());
                for (int i = 0; i < steps.Rows.Count; i++)
                {
                    drpStep.Items.Add(new ListItem(GetCache(steps.Rows[i]["steplabel"].ToString().Trim()), steps.Rows[i]["steplabel"].ToString().Trim()));
                }
            }

            if (!oldStep.Equals("all"))
            {
                drpStep.SelectedValue = oldStep;
            }
        }
        #endregion
        #endregion
    }
}